﻿using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using GameFlowManager.Screens;

namespace GameFlowManager.Menus
{
	public class MenuScreen : GameScreen
	{
		#region Constants

		private const string ASSET_BACKBUTTON = "Textures/Icons/BackButton";

		#endregion

		#region Variables

		private SpriteBatch _spriteBatch;
		private List<Menu> _menus;

		#endregion

		#region Constructors

		public MenuScreen()
			: base()
		{
			_menus = new List<Menu>();
		}

		#endregion

		#region Methods

		public void AddMenu(Menu newMenu)
		{
			if (_menus.Count > 0)
			{
				newMenu.Add(new MenuItem() // add the back button
				{
					Icon = Manager.Game.Content.Load<Texture2D>(ASSET_BACKBUTTON),
					Name = "Back",
					Description = "Go to the previous menu.",
					Action = m =>
					{
						_menus.Last().Closed += menu => _menus.Remove(menu);
						_menus.Last().Close();
						var previousMenu = _menus[_menus.Count - 2];
						_menus.Remove(previousMenu);
						_menus.Add(new Menu(Manager.Game));
						_menus.Last().LoadContent();
						_menus.Last().AddRange(previousMenu);
					}
				});

				_menus.Last().Close();
			}

			_menus.Add(newMenu);
			newMenu.LoadContent();
		}

		public override void LoadContent()
		{
			base.LoadContent();
			_spriteBatch = new SpriteBatch(Manager.Game.GraphicsDevice);
		}

		public override void Update(GameTime gameTime)
		{
			_menus.ForEach(menu => menu.Update(gameTime));
			if (_menus.Last().IsClosed)
			{
				ExitScreen(); // exit the screen when the last menu closes
			}
		}

		public override void Draw(GameTime gameTime)
		{
			_spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
			_menus.ForEach(menu => menu.Draw(gameTime, _spriteBatch));
			_spriteBatch.End();
			base.Draw(gameTime);
		}

		#endregion
	}
}